from functools import wraps

from sanic.request import Request

from utils.response import general_json_res

"""
Author: Gaoqiang Du
Description：as filename said, decorators
Date: 2022/2/8 14:26
"""


def param_check(need_params: set):
    """Check the parameters required from the request."""

    def decorator(f):
        @wraps(f)
        async def decorated_function(instance, request, *args, **kwargs):
            if request.method in ["POST", "PUT", "DELETE"]:
                params = request.json.keys()
            else:
                params = request.args.keys()

            if set(need_params) - set(params):
                return general_json_res(400, "forget some params?")

            response = await f(instance, request, *args, **kwargs)
            return response

        return decorated_function

    return decorator


def check_lazy_load_info(f):
    """懒加载信息相关装饰器"""

    @wraps(f)
    async def decorated_function(instance_or_request, *args, **kwargs):
        request = instance_or_request if isinstance(instance_or_request, Request) else args[0]  # noqa
        kwargs["page"] = int(request.args.get("page", 1))
        kwargs["size"] = int(request.args.get("size", 10))
        kwargs["offset"] = (kwargs["page"] - 1) * kwargs["size"]

        response = await f(instance_or_request, *args, **kwargs)
        return response

    return decorated_function


def is_authenticated(f):
    """身份验证"""

    @wraps(f)
    async def decorated_function(instance_or_request, *args, **kwargs):
        request = instance_or_request if isinstance(instance_or_request, Request) else args[0]  # noqa
        if request.ctx.user_id:
            return await f(instance_or_request, *args, **kwargs)
        return general_json_res(
            401, "The identity information has not been initialized.", 401)

    return decorated_function
